﻿package dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import modelDB.Event;

public class EventDAO implements Manageable<Event, Integer> {
	private EntityManager entityManager;

	public EventDAO() {
		entityManager = DatabaseConnector.getEntityManager();
	}

	@Override
	public boolean insert(Event obj) {
		try {
			entityManager.getTransaction().begin();
			entityManager.persist(obj);
			entityManager.getTransaction().commit();

			return true;
		} catch (Exception e) {
		}
		return false;
	}

	@Override
	public boolean update(Event newEvent) {
		try {
			entityManager.getTransaction().begin();

			Event event = entityManager.find(Event.class, newEvent.getId());
			if (event != null) {
				event.setName(newEvent.getName());
				event.setStartDate(newEvent.getStartDate());
				event.setEndDate(newEvent.getEndDate());
				event.setDesignatedCusLv(newEvent.getDesignatedCusLv());
				event.setDiscountProductMap(newEvent.getDiscountProductMap());
				event.setDescription(newEvent.getDescription());
			}

			entityManager.getTransaction().commit();
			return true;
		} catch (Exception e) {
		}
		return false;
	}

	@Override
	public boolean delete(Integer id) {
		try {
			entityManager.getTransaction().begin();

			Event event = entityManager.find(Event.class, id);
			if (event != null) {
				entityManager.remove(event);
			}

			entityManager.getTransaction().commit();
			return true;
		} catch (Exception e) {
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Event> selectAll() {
		Query query = entityManager.createQuery("SELECT e FROM Event e");
		return query.getResultList();
	}

	@Override
	public Event findByID(Integer id) {
		return entityManager.find(Event.class, id);
	}

}
